package ntrees.hu.oauthtest;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class OauthTestActivity extends Activity {
	
	private String TAG = "OauthTestActivity";
	private int REQUEST_CODE_AUTH = 0;
	
	private static final String API_KEY = "b2585844587c491f89a5303ac23a119d";
	private static final String SECRET_KEY = "3dcdaebbaac341f880bd0e7ab0263778";
	private static final String APP_ID = "169705";
	//private SessionKeyManager mSessionKeyManager = new SessionKeyManager();
	AccessTokenManager mAccessTokenManager;
	
	void init(Context ctx) {
		mAccessTokenManager = new AccessTokenManager(ctx);
		if (mAccessTokenManager.isSessionKeyValid()) {
			Log.d(TAG, "isSessionKeyValid");
		}
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        init(this);
        
        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent it = new Intent();
				it.setClass(OauthTestActivity.this, AuthActivity.class);
				startActivityForResult(it, REQUEST_CODE_AUTH);
			}
		});
        
        Button btn_req = (Button) findViewById(R.id.button_req);
        btn_req.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//requestData();
				getAlbums(null, new EntryHandler() {

					@Override
					public void handleEntry(Entry entry) {
						// TODO Auto-generated method stub
						RenrenAlbumEntry album = (RenrenAlbumEntry)entry;
						Log.d(TAG, "album: " + album.name);
					}
					
				});
			}
		});
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_AUTH) {
			if (resultCode == RESULT_OK) {
				Bundle values = data.getExtras();
				Log.d(TAG, values.toString());
				//values.get("access_token");
				new SessionKeyThread((String)values.get("access_token")).start();
			}
		}
	}
    
    class SessionKeyThread extends Thread {
    	String token;
    	
    	SessionKeyThread(String authToken) {
    		token = authToken;
    	}
    	public void run() {
    		//SessionKeyManager skm = new SessionKeyManager();
    		Looper.getMainLooper().prepare();
    		mAccessTokenManager.updateAccessToken(token);
    		Log.d(TAG, "user: " + mAccessTokenManager.getUid());
    		Toast.makeText(OauthTestActivity.this, String.valueOf(mAccessTokenManager.getUid()), Toast.LENGTH_LONG).show();
    	}
    }

    private final GDataClient.Operation mOperation = new GDataClient.Operation();
    private final String BASE_URL = "http://api.renren.com/restserver.do";
    
    void getAlbums(RenrenUserEntry user, EntryHandler handler) {
    	Bundle params = new Bundle();
		params.putString("method", "photos.getAlbums");
		String uid;
		if (user != null)
			uid = String.valueOf(user.uid);
		else
			uid = String.valueOf(mAccessTokenManager.getUid());
		params.putString("uid", String.valueOf(mAccessTokenManager.getUid()));
    	String response = requestJSON(params);
    	Log.d(TAG, response);
    	AlbumGetResponseBean bean = new AlbumGetResponseBean(response);
    	List<RenrenAlbumEntry> albums = bean.getAlbums();
    	for (RenrenAlbumEntry entry: albums) {
    		handler.handleEntry(entry);
    	}
    }
	
    public String requestJSON(Bundle parameters) {
		return this.request(parameters, "json");
	}
    
	private String request(Bundle parameters, String format) {
		parameters.putString("format", format);
		if (isSessionKeyValid()) {
			parameters.putString("session_key", mAccessTokenManager.getSessionKey());
		}
		
		this.prepareParams(parameters);
		logRequest(parameters);
		String response = Util.openUrl(BASE_URL, "POST", parameters);
		logResponse(parameters.getString("method"), response);
		return response;
	}
    
	private void prepareParams(Bundle params) {
		params.putString("api_key", API_KEY);
		params.putString("v", "1.0");
		params.putString("call_id", String.valueOf(System.currentTimeMillis()));
		params.putString("xn_ss", "1");// sessionSecret作为加密密钥

		StringBuffer sb = new StringBuffer();
		Set<String> keys = new TreeSet<String>(params.keySet());
		for (String key : keys) {
			sb.append(key);
			sb.append("=");
			sb.append(params.getString(key));
		}
		sb.append(mAccessTokenManager.getSessionSecret());
		params.putString("sig", Util.md5(sb.toString()));
	}
	
	/**
	 * 记录请求log
	 */
	private void logRequest(Bundle params) {
		if(params != null) {
			String method = params.getString("method");
			if(method != null) {
				StringBuffer sb = new StringBuffer();
				sb.append("method=").append(method).append("&").append(params.toString());
				Log.i(TAG, sb.toString());
			} else {
				Log.i(TAG, params.toString());
			}
		}		
	}
	
	/**
	 * 记录响应log
	 * @param response
	 */
	private void logResponse(String method, String response) {
		if(method != null && response != null) {
			StringBuffer sb = new StringBuffer();
			sb.append("method=").append(method).append("&").append(response);
			Log.i(TAG, sb.toString());
		}
	}
	
	public boolean isSessionKeyValid() {
		return this.mAccessTokenManager.isSessionKeyValid();
	}
	
    public interface EntryHandler {
        void handleEntry(Entry entry);
    }
}